package com.adams.action.sys;

import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.codec.digest.DigestUtils;

import com.adams.access.db.bean.User;
import com.adams.action.view.ViewAction;
import com.adams.common.BaseAction;
import com.adams.common.Constants;
import com.adams.custom.page.mgt.service.ViewParseService;
import com.adams.custom.page.util.ViewConstant;
import com.adams.log.service.OptLogService;
import com.adams.user.service.UserService;

/**
 * 
 * 
 * File Name : UserAction.java
 * 
 * @Description : 用户管理类
 * @author 902990封文进
 */
public class UserAction extends BaseAction
{

	private ViewParseService viewParseService;

	private UserService userService;

	private OptLogService optLogService;

	private int menuId;

	private String gridPanelId;

	private String viewEventId;

	private String formPanelId;

	private String viewItemId;

	private String searchPanelId;

	/**
	 * 
	 * Description : 显示布局
	 * 
	 * @return String
	 * @throws Exception
	 * 
	 */
	@SuppressWarnings("unchecked")
	public String listPanel() throws Exception
	{
		// Map map = viewParseService.getParseViewByMenuId(getUserId(), menuId);
		// write(JSONObject.fromObject(map).toString());
		write(viewParseService.getParseViewJSONByMenuId(getUserId(), menuId));
		return null;
	}

	/**
	 * Description : 显示查询条字段信息
	 * 
	 * @return
	 * @throws Exception
	 * 
	 */
	public String listSearchItem() throws Exception
	{
		// Map map = viewParseService.getParseSearchItems(getUserId(), menuId,
		// searchPanelId);
		// write(JSONObject.fromObject(map).toString());
		write(viewParseService.getParseSearchItemsJSON(getUserId(), menuId,
				searchPanelId));
		return null;
	}

	/**
	 * 
	 * Description : 显示元素
	 * 
	 * @return String
	 * @throws Exception
	 * 
	 */
	public String listGridStructure() throws Exception
	{
		// Map map = viewParseService.getParseGrids(getUserId(), gridPanelId);
		// write(JSONObject.fromObject(map).toString());
		write(viewParseService.getParseGridsJSON(getUserId(), gridPanelId));
		return null;
	}

	/**
	 * 
	 * Description : 显示数据
	 * 
	 * @return String
	 * @throws Exception
	 * 
	 */
	@SuppressWarnings("unchecked")
	public String listGridData() throws Exception
	{
		Map inputMap = ViewAction.requestParameterMap2Map(request);
		inputMap.put(ViewConstant.JSON_GRID_FILTER + "userName_neq",
				Constants.SUPER_USER_NAME);
		Map map = viewParseService.getParseGridDatas(getUserId(), gridPanelId,
				searchPanelId, inputMap);
		write(JSONObject.fromObject(map).toString());
		return null;
	}

	/**
	 * 
	 * Description : 打开面板窗口
	 * 
	 * @return String
	 * @throws Exception
	 * 
	 */
	@SuppressWarnings("unchecked")
	public String openPanelWindow() throws Exception
	{

		List<Map> mapList = ViewAction.getDataMap(request);
		Map inputMap = null;
		if (mapList.size() > 0)
		{
			inputMap = ViewAction.getDataMap(request).get(0);
		}
		Map map = viewParseService.getParseViewByEventId(getUserId(), menuId,
				viewEventId, inputMap);
		write(JSONObject.fromObject(map).toString());

		return null;

	}

	/**
	 * 
	 * Description : 查询角色
	 * 
	 * @return String
	 * @throws Exception
	 * 
	 */
	@SuppressWarnings("unchecked")
	public String queryRole() throws Exception
	{

		Map map = viewParseService.getParseDynamicCombo(getUserId(), menuId,
				viewItemId);
		write(JSONObject.fromObject(map).toString());

		return null;
	}

	/**
	 * 
	 * Description : 添加用户
	 * 
	 * @return String
	 * @throws Exception
	 * 
	 */
	@SuppressWarnings("unchecked")
	public String add() throws Exception
	{

		Map inputMap = ViewAction.requestParameterMap2Map(request);

		String userName = (String) inputMap.get("userName");
		String password = (String) inputMap.get("password");
		// 用户名不允许有空格
		if (userName.indexOf(" ") >= 0)
		{
			sendFailureMessage(Constants.USER_NAME_HAS_BLANK);
			return null;
		}
		// 密码不允许有空格
		if (password.indexOf(" ") >= 0)
		{
			sendFailureMessage(Constants.PASSWORD_HAS_BLANK);
			return null;
		}
		// 检查是否有中文
		for (int i = 0; i < password.length(); i++)
		{
			if (password.substring(i, i + 1).matches("[\\u4e00-\\u9fbb]+"))
			{
				sendFailureMessage(Constants.PASSWORD_HAS_CHINESE);
				return null;
			}
		}

		User user = userService.queryByName(userName);
		if (user != null)
		{
			sendFailureMessage(Constants.EXIST_USER_NAME);
		} else
		{
			// MD5加密
			inputMap.put("password", DigestUtils.md5Hex(password));
			Map map = viewParseService.saveOrUpdateDataInViewForm(getUserId(),
					menuId, formPanelId, inputMap);
			write(JSONObject.fromObject(map).toString());
			// 记录日志
			createLog("addUser", "user name:" + userName);
		}
		return null;
	}

	/**
	 * 
	 * Description : 更新用户
	 * 
	 * @return String
	 * @throws Exception
	 * 
	 */
	@SuppressWarnings("unchecked")
	public String update() throws Exception
	{

		Map inputMap = ViewAction.requestParameterMap2Map(request);

		String id = (String) inputMap.get("id");
		String userName = (String) inputMap.get("userName");
		String password = (String) inputMap.get("password");

		if (userName.indexOf(" ") >= 0)
		{
			sendFailureMessage(Constants.USER_NAME_HAS_BLANK);
			return null;
		}

		if (password.indexOf(" ") >= 0)
		{
			sendFailureMessage(Constants.PASSWORD_HAS_BLANK);
			return null;
		}
		// 检查是否有中文
		for (int i = 0; i < password.length(); i++)
		{
			if (password.substring(i, i + 1).matches("[\\u4e00-\\u9fbb]+"))
			{
				sendFailureMessage(Constants.PASSWORD_HAS_CHINESE);
				return null;
			}
		}
		User user = userService.queryByName(userName);
		if (user != null && !user.getId().toString().equals(id))
		{
			sendFailureMessage(Constants.EXIST_USER_NAME);
		} else
		{
			user = userService.queryById(new Long(id));
			// MD5加密
			if (!user.getPassword().equals(password))
			{
				inputMap.put("password", DigestUtils.md5Hex(password));
			}
			Map map = viewParseService.saveOrUpdateDataInViewForm(getUserId(),
					menuId, formPanelId, inputMap);
			write(JSONObject.fromObject(map).toString());

			// 记录日志
			createLog("updateUser", "user name:" + userName);
		}
		return null;
	}

	public String updatePassword() throws Exception
	{
		String oldPassword = request.getParameter("oldPassword");
		String newPassword = request.getParameter("newPassword");
		String confirmPassword = request.getParameter("confirmPassword");

		// 数据验证
		if (!newPassword.equals(confirmPassword))
		{
			sendFailureMessage(Constants.NEW_PASSWORD_ERROR);
			return null;
		}
		if (newPassword.indexOf(" ") >= 0)
		{
			sendFailureMessage(Constants.PASSWORD_HAS_BLANK);
			return null;
		}
		// 检查是否有中文
		for (int i = 0; i < newPassword.length(); i++)
		{
			if (newPassword.substring(i, i + 1).matches("[\\u4e00-\\u9fbb]+"))
			{
				sendFailureMessage(Constants.PASSWORD_HAS_CHINESE);
				return null;
			}
		}
		// 检查旧密码是否正确
		String userName = getUserName();
		User user = userService.queryByName(userName);
		if (!user.getPassword().equals(DigestUtils.md5Hex(oldPassword)))
		{
			sendFailureMessage(Constants.OLD_PASSWORD_ERROR);

		} else
		{
			user.setPassword(DigestUtils.md5Hex(newPassword));
			userService.updateUser(user);

			// 记录日志
			createLog("updatePassword", "user name:" + userName);
			sendSuccessMessage(Constants.UPDATE_SUCCESS);
		}
		return null;
	}

	/**
	 * 
	 * Description : 删除用户
	 * 
	 * @return String
	 * @throws Exception
	 * 
	 */
	@SuppressWarnings("unchecked")
	public String delete() throws Exception
	{
		// 过滤下，不要把自己删除掉。
		List<Map> mapList = ViewAction.getDataMap(request);
		if (mapList.size() == 1)// 只删除自己一条记录时，提示不能删除
		{
			if (mapList.get(0).get("userName").equals(getUserName()))
			{
				sendFailureMessage(Constants.NO_PERMIT_DELETE_ME);
				return null;
			}
		} else
		// 多选删除时，过滤掉自己
		{
			for (int i = 0; i < mapList.size(); i++)
			{
				if (mapList.get(i).get("userName").equals(getUserName()))
				{
					mapList.remove(i);
					break;
				}
			}
		}
		viewParseService
				.deleteDataByViewForm(getUserId(), viewEventId, mapList);

		// 记录日志
		StringBuilder userNames = new StringBuilder();
		for (Map map : mapList)
		{
			userNames.append(map.get("userName") + ",");
		}
		createLog("deleteUser", "user name:"
				+ userNames.substring(0, userNames.length() - 1));

		sendSuccessMessage(Constants.DELETE_SUCCESS);

		return null;
	}

	/**
	 * Description : 得到用户详细数据
	 * 
	 * @return String
	 * @throws Exception
	 * 
	 */
	@SuppressWarnings("unchecked")
	public String get() throws Exception
	{

		List<Map> mapList = ViewAction.getDataMap(request);
		Map inputMap = null;
		if (mapList.size() > 0)
		{
			inputMap = ViewAction.getDataMap(request).get(0);
		}
		Map map = viewParseService.getDataByViewForm(getUserId(), menuId,
				formPanelId, inputMap);
		write(JSONObject.fromObject(map).toString());

		return null;
	}

	// /////////////////////属性设置/////////////////////////

	public void setMenuId(int menuId)
	{
		this.menuId = menuId;
	}

	public void setViewParseService(ViewParseService viewParseService)
	{
		this.viewParseService = viewParseService;
	}

	public void setUserService(UserService userService)
	{
		this.userService = userService;
	}

	public void setOptLogService(OptLogService optLogService)
	{
		this.optLogService = optLogService;
	}

	public void setViewEventId(String viewEventId)
	{
		this.viewEventId = viewEventId;
	}

	public void setViewItemId(String viewItemId)
	{
		this.viewItemId = viewItemId;
	}

	public void setFormPanelId(String formPanelId)
	{
		this.formPanelId = formPanelId;
	}

	public void setGridPanelId(String gridPanelId)
	{
		this.gridPanelId = gridPanelId;
	}

	public void setSearchPanelId(String searchPanelId)
	{
		this.searchPanelId = searchPanelId;
	}
}
